<template>
  <div class="checkout-container">
    <!-- 顶部导航栏 -->
    <div class="checkout-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/cart' }">购物车</el-breadcrumb-item>
        <el-breadcrumb-item>结算</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 主要内容区 -->
    <div class="checkout-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="error" class="error-container">
        <el-alert :title="error" type="error" show-icon />
        <el-button type="primary" @click="fetchCartItems">重新加载</el-button>
      </div>

      <div v-else-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="购物车为空，快去选购商品吧！" />
        <el-button type="primary" @click="navigateToHome">
          去购物
        </el-button>
      </div>

      <div v-else class="checkout-form">
        <!-- 左侧信息表单 -->
        <div class="checkout-left">
          <!-- 收货地址 -->
          <div class="form-section">
            <h3>收货地址</h3>
            <el-form :model="shippingAddress" ref="shippingAddressFormRef" :rules="addressRules">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="姓氏" prop="lastName">
                    <el-input v-model="shippingAddress.lastName" placeholder="请输入姓氏" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="名字" prop="firstName">
                    <el-input v-model="shippingAddress.firstName" placeholder="请输入名字" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="shippingAddress.phone" placeholder="请输入手机号码" />
              </el-form-item>
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="shippingAddress.address" placeholder="请输入详细地址" />
              </el-form-item>
              <el-form-item label="补充地址（可选）">
                <el-input v-model="shippingAddress.addressLine2" placeholder="请输入补充地址" />
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="城市" prop="city">
                    <el-input v-model="shippingAddress.city" placeholder="请输入城市" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="省/州" prop="state">
                    <el-input v-model="shippingAddress.state" placeholder="请输入省/州" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="邮政编码" prop="postalCode">
                    <el-input v-model="shippingAddress.postalCode" placeholder="请输入邮政编码" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="国家" prop="country">
                <el-input v-model="shippingAddress.country" placeholder="请输入国家" />
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="useSameBillingAddress">使用与收货地址相同的账单地址</el-checkbox>
              </el-form-item>
            </el-form>
          </div>

          <!-- 账单地址（如果不与收货地址相同） -->
          <div v-if="!useSameBillingAddress" class="form-section">
            <h3>账单地址</h3>
            <el-form :model="billingAddress" ref="billingAddressFormRef" :rules="addressRules">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="姓氏" prop="lastName">
                    <el-input v-model="billingAddress.lastName" placeholder="请输入姓氏" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="名字" prop="firstName">
                    <el-input v-model="billingAddress.firstName" placeholder="请输入名字" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="billingAddress.phone" placeholder="请输入手机号码" />
              </el-form-item>
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="billingAddress.address" placeholder="请输入详细地址" />
              </el-form-item>
              <el-form-item label="补充地址（可选）">
                <el-input v-model="billingAddress.addressLine2" placeholder="请输入补充地址" />
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="城市" prop="city">
                    <el-input v-model="billingAddress.city" placeholder="请输入城市" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="省/州" prop="state">
                    <el-input v-model="billingAddress.state" placeholder="请输入省/州" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="邮政编码" prop="postalCode">
                    <el-input v-model="billingAddress.postalCode" placeholder="请输入邮政编码" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 支付方式 -->
          <div class="form-section">
            <h3>支付方式</h3>
            <el-radio-group v-model="paymentMethod">
              <el-radio label="credit_card">信用卡</el-radio>
              <el-radio label="paypal">PayPal</el-radio>
              <el-radio label="bank_transfer">银行转账</el-radio>
            </el-radio-group>
          </div>

          <!-- 备注 -->
          <div class="form-section">
            <h3>备注</h3>
            <el-input v-model="notes" type="textarea" placeholder="请输入备注信息" />
          </div>
        </div>

        <!-- 右侧商品列表 -->
        <div class="checkout-right">
          <h3>订单详情</h3>
          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <img :src="item.image" alt="商品图片" class="item-image" />
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-price">{{ item.price }}</div>
              <div class="item-quantity">数量: {{ item.quantity }}</div>
            </div>
          </div>
          <div class="total-price">
            <span>总价: {{ totalPrice }}</span>
          </div>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { orderService } from '@/api/orderService';
import { cartService } from '@/api/cartService';
import { useAuthStore } from '@/stores/auth';

export default {
  setup() {
    const router = useRouter();
    const authStore = useAuthStore();

    const cartItems = ref([]);
    const loading = ref(true);
    const error = ref(null);

    // 定义表单ref（需要在使用前定义）
    const shippingAddressFormRef = ref(null);
    const billingAddressFormRef = ref(null);

    const shippingAddress = ref({
      firstName: '',
      lastName: '',
      phone: '',
      address: '',
      addressLine2: '',
      city: '',
      state: '',
      postalCode: '',
      country: '',
    });

    const billingAddress = ref({
      firstName: '',
      lastName: '',
      phone: '',
      address: '',
      addressLine2: '',
      city: '',
      state: '',
      postalCode: '',
      country: '',
    });

    const useSameBillingAddress = ref(true);
    const paymentMethod = ref('credit_card');
    const notes = ref('');

    const addressRules = {
      lastName: [
        { required: true, message: '请输入姓氏', trigger: 'blur' }
      ],
      firstName: [
        { required: true, message: '请输入名字', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入详细地址', trigger: 'blur' }
      ],
      city: [
        { required: true, message: '请输入城市', trigger: 'blur' }
      ],
      postalCode: [
        { required: true, message: '请输入邮政编码', trigger: 'blur' }
      ],
      country: [
        { required: true, message: '请输入国家', trigger: 'blur' }
      ]
    };

    const totalPrice = computed(() => {
      return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0);
    });

    const fetchCartItems = async () => {
      if (!authStore.isAuthenticated) {
        router.push('/login');
        return;
      }
      
      try {
        loading.value = true;
        error.value = null;

        // 从后端获取购物车数据
        const response = await cartService.getCart();
        cartItems.value = response.data.cartItems.map(item => ({
          id: item.id,
          name: item.product.name,
          price: item.product.price,
          quantity: item.quantity,
          image: item.product.images?.[0] || ''
        }));
      } catch (err) {
        error.value = err.message;
      } finally {
        loading.value = false;
      }
    };

    const navigateToHome = () => {
      router.push('/');
    };

    // 提交订单前验证购物车
    const validateCartBeforeSubmit = async () => {
      try {
        // 重新获取购物车数据确认
        const cartResponse = await cartService.getCart();
        if (!cartResponse.data.cartItems || cartResponse.data.cartItems.length === 0) {
          ElMessage.error('购物车为空，请先添加商品');
          return false;
        }
        return true;
      } catch (error) {
        console.error('验证购物车失败:', error);
        ElMessage.error('验证购物车失败，请重试');
        return false;
      }
    };

    // 提交订单
    const submitOrder = async () => {
      if (!authStore.isAuthenticated) {
        ElMessage.error('请先登录');
        router.push('/login');
        return;
      }
      
      try {
        // 验证表单
        await Promise.all([
          shippingAddressFormRef.value?.validate(),
          !useSameBillingAddress.value && billingAddressFormRef.value?.validate()
        ]);
        
        // 验证购物车不为空
        const isCartValid = await validateCartBeforeSubmit();
        if (!isCartValid) {
          return;
        }
        
        // 创建订单
        const orderData = {
          shippingAddress: {
            ...shippingAddress.value,
            firstName: shippingAddress.value.firstName,
            lastName: shippingAddress.value.lastName,
            phone: shippingAddress.value.phone,
            address: shippingAddress.value.address,
            addressLine2: shippingAddress.value.addressLine2,
            city: shippingAddress.value.city,
            state: shippingAddress.value.state,
            postalCode: shippingAddress.value.postalCode,
            country: shippingAddress.value.country
          },
          billingAddress: useSameBillingAddress.value 
            ? { ...shippingAddress.value } 
            : { ...billingAddress.value },
          paymentMethod: paymentMethod.value,
          notes: notes.value
        };
        
        const response = await orderService.createOrder(orderData);
        ElMessage.success('订单创建成功');
        // 使用正确的订单ID字段进行跳转
        router.push(`/order/${response.data.order.id}`);
      } catch (error) {
        console.error('创建订单失败:', error);
        ElMessage.error('创建订单失败: ' + (error.response?.data?.message || error.message));
      }
    };

    // 在组件挂载时获取购物车数据
    onMounted(() => {
      fetchCartItems();
    });

    return {
      cartItems,
      loading,
      error,
      shippingAddress,
      billingAddress,
      useSameBillingAddress,
      paymentMethod,
      notes,
      addressRules,
      totalPrice,
      fetchCartItems,
      navigateToHome,
      submitOrder,
      shippingAddressFormRef,
      billingAddressFormRef
    };
  }
};
</script>